package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.pojo.vo.ApprovalFormVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2023-01-04
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    BorrowerAttachService borrowerAttachService;
    @Resource
    UserInfoService userInfoService;
    @Resource
    UserIntegralService userIntegralService;
    @Resource
    DictService dictService;

    @Override
    public void saveBorrower(BorrowerVO borrowerVO, String token) {
        Long userId = JwtUtils.getUserId(token);
        //查询会员数据
        UserInfo userInfo = userInfoService.getById(userId);
        //获取borrower信息保存到借款人信息表
        Borrower borrower = new Borrower();
        //可以将一个对象的相同类型属性名的属性值拷贝给另一个对象
        BeanUtils.copyProperties(borrowerVO,borrower);
        borrower.setUserId(userId);
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        this.save(borrower);
        //获取附件信息保存到附件表中
        //一共四个附件：
        String carUrl = borrowerVO.getCarUrl();
        String houseUrl = borrowerVO.getHouseUrl();
        String idcard1Url = borrowerVO.getIdcard1Url();
        String idcard2Url = borrowerVO.getIdcard2Url();

        BorrowerAttach borrowerAttach = new BorrowerAttach();
        borrowerAttach.setBorrowerId(borrower.getId());//附件的借款人id
        if(StringUtils.isNotEmpty(carUrl)){
            borrowerAttach.setImageUrl(carUrl);
            borrowerAttach.setImageName("车");
            borrowerAttach.setImageType("car");
            borrowerAttachService.save(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(houseUrl)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(houseUrl);
            borrowerAttach.setImageName("房产证");
            borrowerAttach.setImageType("house");
            borrowerAttachService.save(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(idcard1Url)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(idcard1Url);
            borrowerAttach.setImageName("身份证正面");
            borrowerAttach.setImageType("idCard1");
            borrowerAttachService.save(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(idcard2Url)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(idcard2Url);
            borrowerAttach.setImageName("身份证反面");
            borrowerAttach.setImageType("idCard2");
            borrowerAttachService.save(borrowerAttach);
        }
    }

    @Override
    public Integer getBorrowerStatus(String token) {
        Long userId = JwtUtils.getUserId(token);
        Borrower borrower = this.getOne(Wrappers.lambdaQuery(Borrower.class)
                .eq(Borrower::getUserId, userId));
        if(borrower==null){
            return 0;
        }
        return borrower.getStatus();
    }

    @Override
    public Page<Borrower> listPage(Integer pageNum, Integer pageSize, String keyword) {
        Page<Borrower> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Borrower> queryWrapper = Wrappers.lambdaQuery(Borrower.class);
        if(StringUtils.isNotEmpty(keyword)){
            //根据关键字 在手机号/姓名/身份证号中模糊匹配查询
            queryWrapper.like(Borrower::getName,keyword)
                    .or().like(Borrower::getMobile,keyword)
                    .or().like(Borrower::getIdCard , keyword);
        }

        this.page(page,queryWrapper);
        return page;
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailById(String id) {
        BorrowerDetailVO vo = new BorrowerDetailVO();
        //1、borrower
        Borrower borrower = this.getById(id);
        BeanUtils.copyProperties(borrower , vo);
        //性别 是否婚配  状态  数据类型不一致 需要手动设置
        vo.setSex(borrower.getSex()==0?"女":"男");
        vo.setMarry(borrower.getMarry()?"是":"否");
        String status;
        switch (borrower.getStatus()){
            case 0:
                status = BorrowerStatusEnum.NO_AUTH.getMsg();
                break;
            case 1:
                status =  BorrowerStatusEnum.AUTH_RUN.getMsg();
                break;
            case 2:
                status =  BorrowerStatusEnum.AUTH_OK.getMsg();
                break;
            default:
                status = BorrowerStatusEnum.AUTH_FAIL.getMsg();
                break;
        }
        vo.setStatus(status);

        //2、borrower_attach:附件
        List<BorrowerAttach> attaches = borrowerAttachService.list(Wrappers.lambdaQuery(BorrowerAttach.class)
                .eq(BorrowerAttach::getBorrowerId, borrower.getId()));
        vo.setBorrowerAttaches(attaches);

        //3、dict
        Dict dict = dictService.getDictByDictCodeAndValue("returnSource", borrower.getReturnSource());
        vo.setReturnSource(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("industry", borrower.getIndustry());
        vo.setIndustry(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("income", borrower.getIncome());
        vo.setIncome(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("education", borrower.getEducation());
        vo.setEducation(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("relation", borrower.getContactsRelation());
        vo.setContactsRelation(dict.getName());

        return vo;
    }

    @Override
    public void approval(ApprovalFormVO approvalFormVO) {

        //更新借款人的认证状态
        Long borrowerId = approvalFormVO.getBorrowerId();
        Integer status = approvalFormVO.getStatus();
        Borrower borrower = new Borrower();
        borrower.setId(borrowerId);
        borrower.setStatus(status);
        this.updateById(borrower);//update borrower set status = 1 where id = borrowerId;
        //查询借款人的会员id
        borrower = this.getById(borrowerId);
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        userInfo.setBorrowAuthStatus(status);
        //判断审批是否通过
        if(status==-1){//审批未通过
            userInfoService.updateById(userInfo);//更新会员借款人状态为认证失败
            return;
        }
        //审批通过
        //更新借款人的会员积分
        //计算审核的积分
        int total = 0;
        List<UserIntegral> userIntegrals = new ArrayList<>();
        total+=approvalFormVO.getInfoIntegral();
        //基本信息积分：
        UserIntegral infoIntegral = new UserIntegral();
        infoIntegral.setUserId(userId);
        infoIntegral.setContent("基本信息积分");
        infoIntegral.setIntegral(approvalFormVO.getInfoIntegral());
        userIntegrals.add(infoIntegral);

        if(approvalFormVO.getIsCarOk()){//boolean类型 用基本类型时属性名不能使用is前缀
            total+= IntegralEnum.BORROWER_CAR.getIntegral();
            UserIntegral carIntegral = new UserIntegral();
            carIntegral.setUserId(userId);
            carIntegral.setContent("车辆信息积分");
            carIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegrals.add(carIntegral);
        }
        if(approvalFormVO.getIsIdCardOk()){//boolean类型 用基本类型时属性名不能使用is前缀
            total+= IntegralEnum.BORROWER_IDCARD.getIntegral();
            UserIntegral idcardIntegral = new UserIntegral();
            idcardIntegral.setUserId(userId);
            idcardIntegral.setContent("身份信息积分");
            idcardIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegrals.add(idcardIntegral);
        }
        if(approvalFormVO.getIsHouseOk()){//boolean类型 用基本类型时属性名不能使用is前缀
            total+= IntegralEnum.BORROWER_HOUSE.getIntegral();
            UserIntegral houseIntegral = new UserIntegral();
            houseIntegral.setUserId(userId);
            houseIntegral.setContent("房产信息积分");
            houseIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegrals.add(houseIntegral);
        }
        userInfo.setIntegral(userInfo.getIntegral()+total);
        userInfoService.updateById(userInfo);
        //保存用户积分日志：
        userIntegralService.saveBatch(userIntegrals);

    }
}
